import router from '@/router'

// 建立整个应用的路由结构
const state = {
  routes: [],
  addRoutes: []
}

// 修复路由路径
const fixRoutesPath = (routes) => {
  if (!routes) return []
  
  return routes.map(route => {
    const newRoute = { ...route }

    // 检查路径并修复
    if (newRoute.path && typeof newRoute.path === 'string') {
      // 完整路径的处理
      if (newRoute.path.includes('/health/check')) {
        newRoute.path = newRoute.path.replace('/health/check', '/health-check')
      } 
      if (newRoute.path.includes('/forum/list')) {
        newRoute.path = newRoute.path.replace('/forum/list', '/forum')
      }
      
      // 相对路径的处理
      if (newRoute.path === 'health/check') {
        newRoute.path = 'health-check'
      } 
      if (newRoute.path === 'forum/list') {
        newRoute.path = 'forum'
      }
    }
    
    // 如果有子路由，递归修复
    if (newRoute.children && newRoute.children.length > 0) {
      newRoute.children = fixRoutesPath(newRoute.children)
    }
    
    return newRoute
  })
}

// 获取当前用户可访问的路由
const filterAsyncRoutes = (routes, role) => {
  const res = []
  
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(role, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, role)
      }
      res.push(tmp)
    }
  })
  
  return res
}

// 检查是否有权限
const hasPermission = (role, route) => {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(role)
  } else {
    return true
  }
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = router.options.routes.concat(routes)
  },
  RESET_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
  },
  FIX_ROUTES: (state) => {
    state.routes = fixRoutesPath(state.routes)
    state.addRoutes = fixRoutesPath(state.addRoutes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 获取所有路由
      const accessedRoutes = router.options.routes

      // 修复路由路径
      const fixedRoutes = fixRoutesPath(accessedRoutes)
      
      commit('SET_ROUTES', fixedRoutes)
      resolve(fixedRoutes)
    })
  },
  fixRoutes({ commit }) {
    commit('FIX_ROUTES')
  }
}

// 更新生成的路由（在getter中使用）
const getFixedRoutes = (state) => {
  return fixRoutesPath(state.routes)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters: {
    fixedRoutes: getFixedRoutes
  }
} 